#联网
# wificonnect.py


import network
import time
import json

def load_config():
    with open('config.json', 'r') as f:
        return json.load(f)

wlan = None

def wifi_connect():
    global wlan
    config = load_config()
    ssid = config['wifi_ssid']
    password = config['wifi_password']

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    if not wlan.isconnected():
        print(f'Connecting to network {ssid}...')
        wlan.connect(ssid, password)
        start_time = time.time()

        while not wlan.isconnected():
            if time.time() - start_time > 10:
                print("WiFi connection timeout")
                return False
            time.sleep(1)

    print('Network connected:', wlan.ifconfig())
    return True

def isWifiConnect():
    return wlan.isconnected()

if __name__ == "__main__":
    wifi_connect()
